package cn.com.server.common.util;


import java.io.IOException;
import java.net.Inet4Address;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


/**
 * 获取访问的真实IP
 */
public class IPUtil {
    static public String getIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (null == ip) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    static public String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }
    
    static public List<String> getRealIP(){
    	List<String> ipsList = new ArrayList<String>();
    	 try {
             for (Enumeration<?> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
                 NetworkInterface item = (NetworkInterface) e.nextElement();
                 //非虚拟非回路并开启状态
                 if((!item.isVirtual()) && item.isUp() && (!item.isLoopback())){
                     for (InterfaceAddress address : item.getInterfaceAddresses()) {
                         if (address.getAddress() instanceof Inet4Address) {
                             Inet4Address inet4Address = (Inet4Address) address.getAddress();
                             //if(inet4Address.isSiteLocalAddress()){
                                 System.out.println(inet4Address.getHostAddress());
                                 ipsList.add(inet4Address.getHostAddress());
                            // }

                         }
                     }
                 }
             }
         } catch (IOException ex) {

         }
		return ipsList;
    }
}

